package com.walleipt.ipt_tools.utils;

import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicInteger;

public class GuidUtils
{
	private static int toInt(byte[] bytes)
	{
		int result = 0;
		for (int i = 0; i < 4; i++)
		{
			result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
		}
		return result;
	}

	private static final int IP;
	static
	{
		int ipadd;
		try
		{
			ipadd = toInt(InetAddress.getLocalHost().getAddress());
		}
		catch (Exception e)
		{
			ipadd = 0;
		}
		IP = ipadd;
	}

	private static AtomicInteger counter = new AtomicInteger() ;

	private static final int JVM = (int) (System.currentTimeMillis() >>> 8);

	protected static int getJVM()
	{
		return JVM;
	}

	protected static int getIP()
	{
		return IP;
	}

	protected static short getHiTime()
	{
		return (short) (System.currentTimeMillis() >>> 32);
	}

	protected static int getLoTime()
	{
		return (int) System.currentTimeMillis();
	}

	protected static String format(int intval)
	{
		String formatted = Integer.toHexString(intval);
		StringBuffer buf = new StringBuffer("00000000");
		buf.replace(8 - formatted.length(), 8, formatted);
		return buf.toString();
	}

	protected static String format(short shortval)
	{
		String formatted = Integer.toHexString(shortval);
		StringBuffer buf = new StringBuffer("0000");
		buf.replace(4 - formatted.length(), 4, formatted);
		return buf.toString();
	}

	public static String generate( String _sep )
	{
		return new StringBuffer(36).append(format(getIP())).append(_sep)
		.append( format(getJVM())).append(_sep).append(format(getHiTime()))
			.append(_sep).append(format(getLoTime())).append(_sep).append(
					format( counter.addAndGet(1) ) ).toString();
	}
	
	public static String generate()
	{
		return generate( "" ) ;
	}
	
	@SuppressWarnings("unused")
	public static boolean isUUID( String _str )
	{
		if( _str == null )
			return false ;
		
		if (_str.length() == 32 )
		{
			_str = _str.substring( 0 , 8 ) + "-" 
				+ _str.substring( 8 , 12 ) + "-"
				+ _str.substring( 12 , 16 ) + "-"
				+ _str.substring( 16 , 20 ) + "-"
				+ _str.substring( 20 ) ;
		}

		if( _str.length() == 36 )
		{
			char c1 = _str.charAt( 8 ) ;
			char c2 = _str.charAt( 13 ) ;
			char c3 = _str.charAt( 18 ) ;
			char c4 = _str.charAt( 23 ) ;
			char c22 = _str.charAt( 17 ) ;
			char c33 = _str.charAt( 22 ) ;
			char c44 = _str.charAt( 31 ) ;
			
			if( c1 == '-' && c2 == '-' && c3 == '-' && c4 == '-' )
			{}
			else if( c1 == '-' && c22 == '-' && c33 == '-' && c44 == '-' )
			{
				_str = _str.substring( 0 , 13 ) + "-" 
					+ _str.substring( 13 , 31 )
					+ _str.substring( 32 ) ;
			}
			else
				return false ;
			
			for (int i = 0; i <36 ; i++)
			{
				int c = _str.charAt(i) | 0x20; 
				if ( !(i == 8 || i == 13 || i==18 || i == 23) )
				{
					byte h = (byte) (c & 0x0f);
					if ( c >= 'a' && c <= 'f')
						h += 9;
					else if (c < '0' || c > '9')
						return false ;
				}
			}
			return true ;
		}
		else
			return false ;
	}
}
